package com.monitor.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.monitor.dao.MessageDao;
import com.monitor.po.Message;
import com.monitor.util.Pager;

@SuppressWarnings("unchecked")
public class MessageDaoImpl implements MessageDao {
	private SessionFactory sessionFactory;

	@Override
	public void addMessage(Message message) throws Exception {
		try {
			this.sessionFactory.getCurrentSession().persist(message);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("exception occured when excuting addMessage()....");
		}
	}

	@Override
	public Pager<Message> getMessageByPhone(String phone, int pageSize, int currentPage) throws Exception {
		try {
			Session sesion = this.sessionFactory.getCurrentSession();
			Query query = sesion.createQuery("select count(*) from Message m where m.phone=:phone").setString("phone", phone);
			int totalCount = ((Number) query.uniqueResult()).intValue();
			int pageCount = (totalCount % pageSize == 0) ? totalCount / pageSize : (totalCount / pageSize) + 1;
			List<Message> list = sesion.createQuery("from Message m where m.phone=:phone order by m.id desc").setString("phone", phone)
					.setFirstResult((currentPage - 1) * pageSize).setMaxResults(pageSize).list();
			Pager<Message> pager = new Pager<Message>(list, currentPage, totalCount, pageCount);
			return pager;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("exception occured when excuting getMessageByPhone()....");
		}
	}

	@Override
	public int deleteMessageByPhone(String phone) throws Exception {
		try {
			return sessionFactory.getCurrentSession().createQuery("delete from Message m where m.phone=:phone").setString("phone", phone)
					.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("exception occured when excuting deleteMessageByPhone()....");
		}
	}

	@Override
	public int deleteMessage(long id, String phone) throws Exception {
		try {
			return sessionFactory.getCurrentSession().createQuery("delete from Message m where m.phone=:phone and m.id=:id")
					.setString("phone", phone).setLong("id", id).executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("exception occured when excuting deleteMessage()....");
		}
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

}
